﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PerfumeShopManagement.DAL;
using PerfumeShopManagement.Model;
using PerfumeShopManagement.Utility;

namespace PerfumeShopManagement.BLL
{
    public class BllAccount : BllAbstractBase<User, string>
    {
        public BllAccount()
            : base()
        {
            User criteria = new User();
            criteria.RoleId = Constants.USER_ROLE;
            items = DalFactory.AccountDAL.GetObjectsByCriteria(criteria);
        }

        private bool contains(User user)
        {
            return items.Contains(user);
        }

        public override List<User> GetAll()
        {
            return items;
        }

        public override User Get(string id)
        {
            throw new NotImplementedException();
        }

        public override List<User> Search(User criteria)
        {
            return DalFactory.AccountDAL.GetObjectsByCriteria(criteria);
        }

        public override bool Save(User obj)
        {
            User user = obj;

            bool updated = false;
            foreach (User item in items)
            {
                if (item.Username == user.Username)
                {
                    item.Password = user.Password;
                    item.RoleId = user.RoleId;
                    item.Name = user.Name;
                    item.PhoneNumber = user.PhoneNumber;
                    item.Address = user.Address;
                    updated = true;
                    DalFactory.AccountDAL.Update(user);

                    return true;
                }
            }

            if (!updated)
            {
                items.Add(user);
                DalFactory.AccountDAL.Insert(user);

                return true;
            }

            return false;
        }

        public override bool DeleteById(string id)
        {
            throw new NotImplementedException();
        }

        public bool Login(string username, string password)
        {
            if (StringUtil.isEmptyOrBlank(username)
                || StringUtil.isEmptyOrBlank(password))
            {
                return false;
            }

            User criteria = new User();
            criteria.Username = username;
            List<User> users = DalFactory.AccountDAL.GetObjectsByCriteria(criteria);

            if (users.Count > 0 && users[0].RoleId == Constants.ADMIN_ROLE)
            {
                if (password == users[0].Password) // Login successfully
                {
                    return true;
                }
            }
            return false;
        }
    }
}
